#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
#define PORT 8080

void *receive_handler(void *arg) {
    int sockfd = *(int *)arg;
    char buffer[BUFFER_SIZE];
    
    while (1) {
        ssize_t bytes = recv(sockfd, buffer, sizeof(buffer)-1, 0);
        if (bytes <= 0) {
            printf("与服务器断开连接\n");
            exit(EXIT_FAILURE);
        }
        buffer[bytes] = '\0';
        printf("%s", buffer);
    }
    return NULL;
}

void show_menu() {
    printf("\n=== 聊天室菜单 ===\n");
    printf("输入消息直接发送\n");
    printf("/list   查看在线用户\n");
    printf("/quit   退出聊天室\n");
    printf("==================\n");
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("使用方法: %s <服务器IP> <昵称>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd;
    struct sockaddr_in server_addr;
    
    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) <= 0) {
        perror("地址转换错误");
        exit(EXIT_FAILURE);
    }

    // 连接服务器
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("连接失败");
        exit(EXIT_FAILURE);
    }

    // 发送昵称
    send(sockfd, argv[2], strlen(argv[2]), 0);

    // 创建接收线程
    pthread_t tid;
    pthread_create(&tid, NULL, receive_handler, (void *)&sockfd);

    show_menu();

    // 处理用户输入
    char input[BUFFER_SIZE];
    while (1) {
        fgets(input, sizeof(input), stdin);
        
        if (strncmp(input, "/quit", 5) == 0) {
            send(sockfd, "/quit", 5, 0);
            break;
        }
        else if (strncmp(input, "/list", 5) == 0) {
            // 请求在线用户列表
            send(sockfd, "/list", 5, 0);
        }
        else {
            send(sockfd, input, strlen(input), 0);
        }
    }

    close(sockfd);
    printf("已断开连接\n");
    return 0;
}